<?php

/**
 * mailing actions.
 *
 * @package    Terapia Vital
 * @subpackage mailing
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class mailingActions extends sfActionsFoxsis
{
	public function executeIndex(sfWebRequest $request)
	{
		return $this->forward('mailing', 'list');
	}

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= MailingTable::consultar($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Url', 'Tag'));

		foreach($this->data as $key => &$r)
		{
			$r['st_mailing'] = ($r['st_mailing'] == 0) ? 'Ativo' : 'Inativo';
			$r['dt_envio'] = format_date($r['dt_envio'], 'p');
			
			$actions = array(
				'edit'	 => link_to(
	    			' ',
					url_for($this->getModuleName().'/edit?id_mailing='.$r['id_mailing']),
					array( 'class' => 'icoEditar' )
    			),
	    		'show' => link_to(
	    			' ',
    				url_for($this->getModuleName().'/show?id_mailing='.$r['id_mailing']),
    				array( 'class' => 'icoVisualizar' )
    			),
	    		'mailsend' => link_to(
	    			' ',
    				url_for($this->getModuleName().'/enviar?id_mailing='.$r['id_mailing']),
    				array( 'class' => 'icoAceitar' )
    			),
				'delete' => link_to(
	    			' ',
    				url_for($this->getModuleName().'/delete?id_mailing='.$r['id_mailing']),
    				array( 'class' => 'icoExcluir delete' )
    			)
    		);
    		$this->data[$key]['act'] = implode(' ', $actions);
		}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


	public function executeList()
	{
		$this->form = new MailingForm();
		$this->colunas	= array(
			$this->form['id_mailing']->renderLabel() => "id_mailing",
			$this->form['nm_mailing']->renderLabel() => "nm_mailing",
			$this->form['st_mailing']->renderLabel() => "st_mailing",
			$this->form['dt_envio']->renderLabel() => "dt_envio",
			"Ações"	=> "act"
		);

		$this->filter = $this->_getFilter();

		$this->setTemplate('index');
	}

	public function executeFilter()
	{
		$filter = new Filtro(
		$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
		sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
		serialize($filter),
		$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

	public function executeShow(sfWebRequest $request)
	{
		$this->mailing = Doctrine::getTable('Mailing')->find(array($request->getParameter('id_mailing')));
		$this->forward404Unless($this->mailing);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->getUser()->setFlash('orientacao', 'As tarefas de email são verificadas de 30 em 30 minutos.');
		$this->form = new MailingForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new MailingForm();

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'new');
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->getUser()->setFlash('orientacao', 'As tarefas de email são verificadas de 30 em 30 minutos.');
		$this->forward404Unless($mailing = Doctrine::getTable('Mailing')->find(array($request->getParameter('id_mailing'))), sprintf('Object mailing does not exist (%s).', $request->getParameter('id_mailing')));
		$this->form = new MailingForm($mailing);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($mailing = Doctrine::getTable('Mailing')->find(array($request->getParameter('id_mailing'))), sprintf('Object mailing does not exist (%s).', $request->getParameter('id_mailing')));
		$this->form = new MailingForm($mailing);

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'edit');
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$mailing = Doctrine::getTable('Mailing')->find($request->getParameter('id_mailing'));
			if($mailing)
				$mailing->delete();
			else 
				throw new Exception(utf8_decode('Não foi possível carregar o Objeto'));

			$result = array(
				'success' => utf8_encode('Operação realizada com sucesso.')
			);
	
			$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
			return $this->renderText(json_encode($result));
		}
		catch(Exception $e)
		{
			$result = array(
				'error' => utf8_encode('Erro ao excluir: ' . $e->getMessage())
			);
	
			$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
			return $this->renderText(json_encode($result));
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
			{
				$mailing = $form->save();
				$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
				$this->redirect('mailing/edit?id_mailing='.$mailing->getIdMailing());
			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}
	}
	
	public function executeEnviar(sfWebRequest $request)
	{
		$id_mailing = $request->getParameter('id_mailing');
		$mailing = Doctrine::getTable('Mailing')->find($id_mailing);
		//shell_exec("/home/terapiav/symfony newsletter:task --id_mailing={$id_mailing}");
		
		$dir_arquivo = sfConfig::get('sf_upload_dir').'/newsletter/'.$id_mailing.'.txt';
		
		$mmgs = MailingTable::carregarMailingEnviar($id_mailing);
		$handle = fopen($dir_arquivo, 'a+');
		
		// pegos os grupos
		foreach($mmgs as $mmg){
			$mg = $mmg['MailingGroup'];
			$m = $mmg['Mailing'];
			
			// para cada grupo eu pegos os usuários
			fwrite($handle, 'Start: ' . date('d/m/Y H:i:s') . "\r\n");
			fwrite($handle, 'Grupo: ' . $mg->getNmMailingGroup() . "\r\n");
			
			// pego os usuários do grupo
			$mls = $mg['MailingList'];
			
			foreach($mls as $ml)
			{
				$this->enviarEmailNewletter($m, $ml, $handle);
				sleep(2);
			}
			
			fwrite($handle, 'Final: ' . date('d/m/Y H:i:s') . "\r\n");
			sleep(10);
		}

		fclose($handle);
		
		$mailing->set('st_mailing', '1');
		$mailing->save();
		
		$this->getUser()->setFlash('mensagem', 'Newsletter enviada com sucesso');
		$this->redirect('mailing/list');
	}
	
	protected function enviarEmailNewletter($m, $ml, $handle)
	{
		// class initialization
	    $mail = new sfMail();
	    $mail->setCharset('iso-8859-1');

	    // definition of the required parameters
	    $mail->setSender('contato@terapiavital.com.br', "TerapiaVital");
	    $mail->setFrom('contato@terapiavital.com.br', "TerapiaVital");
	    $mail->addReplyTo('contato@terapiavital.com.br');
		
	    $mail->addAddress($ml->getDsEmailList(), $ml->getDsNomeList());

	    $mail->setSubject('TerapiaVital | ' . $m->getNmMailing());
	    $mail->setContentType('text/html');
		
	    $msg = str_ireplace('http://', 'http://www.', $m->getDsMailing());
	    $msg .= "<br /><br />
	            Esta é uma mensagem gerada automaticamente pelo sistema.<br />
	            Por favor, não responda. Pois, neste caso, a mesma será descartada.";

	    $mail->setBody($msg);
   	 	$mail->send();
   	 	
   	 	fwrite($handle, $ml->getDsNomeList() . ' = ' . $ml->getDsEmailList() . "\r\n");
	}
}
